package com.example.tangyee.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.example.tangyee.bean.RecipeIngredient;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetRecipeIngredient extends AsyncTask<Void, Void, RecipeIngredient> {

    private static final String TAG = "GetRecipeIngredient";

    private int id;
    private OnPostExecute mExecute;

    public GetRecipeIngredient(int id, OnPostExecute execute){
        this.id = id;
        this.mExecute = execute;
    }

    @Override
    protected RecipeIngredient doInBackground(Void... voids) {
        if (isCancelled()) {
            return null;
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .build();

        StringBuilder stringBuilder = new StringBuilder(ConstantsUtil.GET_RECIPE_INGREDIENT);
        stringBuilder.append("id=" + id);
        Request request = new Request.Builder()
                .url(stringBuilder.toString())
                .build();

        String respStr = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            respStr = response.body().string();

            if (respStr == null) {
                return null;
            }
        } catch (IOException e) {
            Log.e(TAG, "doInBackground: ", e);
        }

        RecipeIngredient ingredient = null;

        try {
            Log.i(TAG, "Received JSON: " + respStr);
            Gson gson = new Gson();
            ingredient = gson.fromJson(respStr, RecipeIngredient.class);
        } catch (NullPointerException npe) {
            Log.e(TAG, "doInBackground: ", npe);
            return null;
        }

        return ingredient;
    }

    @Override
    protected void onPostExecute(RecipeIngredient ingredient) {
        mExecute.onPostExecute(ingredient);
    }

    public void setOnPostExecute(OnPostExecute execute) {
        this.mExecute = execute;
    }

    public interface OnPostExecute {
        void onPostExecute(RecipeIngredient ingredient);
    }
}
